﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
using PlanningGIS.Util.Net;

namespace PlanningGIS.Entry
{
    /// <summary>
    /// 更新实例
    /// </summary>
    public class AutoUpdater
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public AutoUpdater()
        {
            _Config = Application.StartupPath + "\\Update.xml";
        }

        ///// <summary>
        ///// 正在更新
        ///// </summary>
        //public event UpdateDelegate UpdateDoing;

        ///// <summary>
        ///// 更新完成
        ///// </summary>
        //public event UpdateDelegate UpdateFinished;

        /// <summary>
        /// 配置文件
        /// </summary>
        private string _Config = "";

        /// <summary>
        /// 更新路径地址
        /// </summary>
        private string _Url = "";

        /// <summary>
        /// 更新程序的exe路径
        /// </summary>
        private string _UpdateExe = "";

        /// <summary>
        /// Ftp操作对象
        /// </summary>
        public FTPRequest Ftp { get; private set; }

        /// <summary>
        /// 检查系统是否需要更新
        /// </summary>
        /// <returns></returns>
        public bool CheckUpdated()
        {
            if (!File.Exists(_Config)) return false;
            XDocument doc = XDocument.Load(_Config);
            XElement root = doc.Root;
            string up = root.Element("AutoUpdate").Value.ToString();
            if (!"1".Equals(up)) return false;
            root.Element("MainExe").Value = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
            doc.Save(_Config);
            _UpdateExe = root.Element("UpdateExe").Value.ToString();
            _Url = root.Element("Url").Value.ToString();
            if (string.IsNullOrWhiteSpace(_Url)) return false;
            Ftp = new FTPRequest(new Uri(_Url), root.Element("UserName").Value.ToString(), root.Element("Password").Value.ToString());
            List<FileStruct> files = Ftp.ListFiles();
            if (files == null || files.Count == 0) return false;
            string nm = files.Select(t => t.Name).Max();
            string[] ns = nm.Split('_');
            if (ns.Length < 2) return false;
            if (ns[1].CompareTo(root.Element("Version").Value.ToString()) <= 0) return false;
            return true;
        }

        /// <summary>
        /// 启动自动更新
        /// </summary>
        public void StartExe()
        {
            if (!string.IsNullOrWhiteSpace(_UpdateExe)) Process.Start(_UpdateExe);

        }
    }

    /// <summary>
    /// 更新事件委托
    /// </summary>
    /// <param name="value"></param>
    public delegate void UpdateDelegate(dynamic value);
}